package com.jhw.ymcc.service.impl;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.common.models.AlipayTradeCloseResponse;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.jhw.ymcc.domain.PayFlow;
import com.jhw.ymcc.domain.PayOrder;
import com.jhw.ymcc.dto.PayNotifyLocalTxParamDto;
import com.jhw.ymcc.exception.GlobalErrorCode;
import com.jhw.ymcc.mapper.PayOrderMapper;
import com.jhw.ymcc.service.IPayFlowService;
import com.jhw.ymcc.service.IPayOrderService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jhw.ymcc.util.AssertUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jhw
 * @since 2022-10-16
 */
@Slf4j
@Service
public class PayOrderServiceImpl extends ServiceImpl<PayOrderMapper, PayOrder> implements IPayOrderService {

    @Autowired
    private IPayOrderService payOrderService;

    @Autowired
    private IPayFlowService payFlowService;

    @Override
    public PayOrder selectByOrderNo(String orderNo) {
        Wrapper<PayOrder> wrapper = new EntityWrapper<>();
        wrapper.eq("order_no", orderNo);
        return selectOne(wrapper);
    }

    @Override
    public void cancelOrder(String orderNo, PayOrder payOrder) {
        try {
            AlipayTradeCloseResponse close = Factory.Payment.Common().close(orderNo);
            if (!close.code.equals("10000")){
                log.error("订单关闭失败，订单号为：{}", orderNo);
            }
            payOrder.setPayStatus(PayOrder.CANCEL_PAY_STATUS);
            payOrderService.updateById(payOrder);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void asyncNotifyHandler(PayNotifyLocalTxParamDto payNotifyLocalTxParamDto) {
        PayFlow payFlow = payNotifyLocalTxParamDto.getPayFlow();
        PayOrder payOrder = payNotifyLocalTxParamDto.getPayOrder();

        PayOrder payOrderTmp = selectByOrderNo(payOrder.getOrderNo());
        AssertUtil.isNotNull(payOrderTmp, GlobalErrorCode.ERROR);

        synchronized (payOrder.getOrderNo()){
            if (PayOrder.WAIT_PAY_STATUS.equals(payOrderTmp.getPayStatus())){
                updateById(payOrder);
                payFlowService.insert(payFlow);
            }
        }
    }
}
